/*
 * history.c
 *
 *  Created on: 2009-8-7
 *      Author: wyb
 */

#include "history.h"

struct double_array *analyze_history(struct fft_cosine *history_cosine, int N) {
	double min, max, temp;

	if (history_cosine->N <= 1)
		return NULL;

	min = history_cosine->A[1][0];
	max = history_cosine->A[1][0];
	int i;
	for (i = 2; i < history_cosine->N; i++) {
		if (history_cosine->A[i][0] < min) {
			min = history_cosine->A[i][0];
		} else if (history_cosine->A[i][0] > max) {
			max = history_cosine->A[i][0];
		}
	}

	temp = (pow(max, 2) - pow(min, 2)) * LIMIT_PERCENT + pow(min, 2);

	int num = 0;
	for (i = 0; i < history_cosine->N; i++) {
		if ((history_cosine->A[i][2] <= 0.5) && (history_cosine->A[i][2]
				>= (double) MIN_FREQUENCY / N) && (pow(history_cosine->A[i][0],
				2) >= temp)) {
			num++;
		}
	}

	struct double_array *period;
	period = malloc(sizeof(struct double_array));
	period->N = num;
	period->data = malloc(period->N * sizeof(double));

	int j;
	for (i = 0, j = 0; i < history_cosine->N; i++) {
		if ((history_cosine->A[i][2] <= 0.5) && (history_cosine->A[i][2]
				>= (double) MIN_FREQUENCY / N) && (pow(history_cosine->A[i][0],
				2) >= temp)) {
			period->data[j] = 1.0 / history_cosine->A[i][2];
			j++;
		}
	}

	return period;
}

void history_filter(struct double_array *history) {
	if (history->N < ERROR_N) {
		return;
	}

	double average = 0.0;
	int i;
	for (i = 0; i < ERROR_N; i++) {
		average += history->data[i];
	}
	average = average / ERROR_N;

	for (i = 0; i < ERROR_N / 2; i++) {
		if (history->data[i] >= ERROR * average) {
			history->data[i] = REVISE * average;
		}
	}

	for (i = ERROR_N / 2; i < history->N - ERROR_N + ERROR_N / 2; i++) {
		average -= history->data[i - ERROR_N / 2] / ERROR_N;
		average += history->data[i + ERROR_N - ERROR_N / 2] / ERROR_N;
		if (history->data[i] >= ERROR * average) {
			history->data[i] = REVISE * average;
		}
	}

	for (i = history->N - ERROR_N + ERROR_N / 2; i < history->N; i++) {
		if (history->data[i] >= ERROR * average) {
			history->data[i] = REVISE * average;
		}
	}
}
